package registnet.base;

import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Vector;

import resources.Constants;

/**
 * An implementation of a transcript of record.
 */
public class Transcript extends AbstractTranscript {

	/**
	 * Default constructor which creates an "empty" transcript of records.
	 */
	public Transcript(){
		studentNumber = "";
		curriculum = null;
		courses = new Vector<ICourse>();
	}
	
	/**
	 * Creates a transcript to be associated with the student with the given student number.
	 * @param studentNumber
	 */
	public Transcript(String studentNumber){
		this.studentNumber = studentNumber;
	}
	
	/**
	 * Updates the reexam grade of a course with the given course code.
	 * @param courseCode
	 * @param grade
	 */
	public void updateReexamCourse(String courseCode, double grade){
		for(int i=courses.size()-1; i>=0; i--){
			CourseTaken courseTaken = (CourseTaken)courses.get(i);
			if(courseTaken.getCourseCode().equals(courseCode) && (courseTaken.getGrade()==Constants.MAP_GRADE_KEY.get("INC.")  || courseTaken.getGrade()==Constants.MAP_GRADE_KEY.get("4.00")) && courseTaken.getReExam()==0){
				((CourseTaken)courses.get(i)).setReExam(grade);
				break;
			}
		}
	}
	
	/**
	 * Prints a basic description of the transcript of records.
	 */
	public void print(){
		System.out.println("[check] transcript: "+studentNumber+" "+courses.size());
		ListIterator<ICourse> li = courses.listIterator();
		while(li.hasNext()){
			ICourse course = li.next();
			System.out.println("[check] courseTaken: "+course.getCourseCode());
		}
	}
	
	/**
	 * Returns the latest grade in a course with the given course code.
	 * @param courseCode
	 * @return the latest grade in a course with the given course code
	 */
	public double getLatestGrade(String courseCode){
		double latestGrade = 0;
		ListIterator<ICourse> li = this.courses.listIterator();
		HashMap<String, ICourse> tempMap = new HashMap<String, ICourse>();
		List<ICourse> tempList = new Vector<ICourse>();
		ICourse latestCourse = null;
		while(li.hasNext()){
			ICourse course = li.next();
			if (course.getCourseCode().equals(courseCode)){
				if(!tempMap.containsKey(course.getCourseCode())){
					tempMap.put(course.getCourseCode(), course);
				}
				else{
					tempList.add(tempMap.get(course.getCourseCode()));
					tempMap.remove(course.getCourseCode());
					tempMap.put(course.getCourseCode(), course);
				}
				if (((CourseTaken)course).getReExam() != 0)
					latestGrade = ((CourseTaken)course).getReExam();
				else
					latestGrade = ((CourseTaken)course).getGrade();
				latestCourse = course;
			}
		}
		
		for(int i=0; i<tempList.size(); i++){
			this.courses.remove(tempList.get(i));
		}
		
		this.courses.remove(latestCourse);
		
		return latestGrade;

	}
	
}
